import Vue from 'vue';
import config from './config.js';
import store from '@/store/index.js';

import {RouterMount,createRouter} from 'uni-simple-router';

// 初始化
const router = createRouter({
	platform: process.env.VUE_APP_PLATFORM,  
	routes: [...ROUTES]
});

//全局路由前置守卫
router.beforeEach((to, from, next) => {
	//权限控制操作
	console.info(store.store);
	let cacheData = uni.getStorageSync('cacheData') || undefined;
	let token = '';
	if(cacheData){
		 token = cacheData.vuex_token ? cacheData.vuex_token : '';
	}
	if (to.meta && to.meta.auth) {
		
		//开启全局登陆拦截
		// //如果token不为空，判断是否有效
		// if (!token) {
		// 	next('/pages/login/login');
		// } else {
		// 	//校验token是否有效
		// 	uni.request({
		// 		url: config.baseUrl + 'api/login/check',
		// 		method: 'GET',
		// 		header: {
		// 			'Authorization': token
		// 		},
		// 		success: (res) => {
		// 			console.log(res.data);
		// 			if(res.data.code == 200){
		// 				next();
		// 			}else{
		// 				uni.setStorageSync('cacheData', '');
		// 				next('/pages/login/login');
		// 			}
		// 		}
		// 	});
			
		// }
		debugger
		//如果token不为空，判断是否有效
		if (token) {
			debugger
			//校验token是否有效
			uni.request({
				url: config.baseUrl + 'api/login/check',
				method: 'GET',
				header: {
					'Authorization': token
				},
				success: (res) => {
					console.log(res.data);
					if(res.data.code == 200){
						next();
					}else{
						uni.setStorageSync('cacheData', '');
						next('/pages/login/login');
					}
				}
			});
		}else{
			next('/pages/login/login');
		}
	} else {
		if (token && to.meta.name == "login") {
			next('/pages/index/index');
		} else {
			next();
		}
	}

})
// 全局路由后置守卫
router.afterEach((to, from) => {
	// console.log(to, "全局路由后置守卫");
})
export {
	router,
	RouterMount
}
